<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      function arrayToTreeRec(arr, parentId = 0) {
        return arr.reduce((newArr, item) => {
          if (item.parentId == parentId) {
            item.children = arrayToTreeRec(arr, item.id);
            newArr.push(item);
          }
          return newArr;
        }, []);
      }
      let source = [
        {
          id: 1,
          parentId: 0,
          name: 'body',
        },
        {
          id: 2,
          parentId: 1,
          name: 'title',
        },
        {
          id: 3,
          parentId: 2,
          name: 'div',
        },
      ];

      console.log(arrayToTreeRec(source, 0));
    </script>
  </body>
</html>
